package com.raja.servingStation.dao;

import com.alibaba.fastjson.JSONObject;
import com.raja.servingStation.datasources.RepairSql2oTemp;
import com.raja.servingStation.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.sql2o.Connection;
import org.sql2o.Query;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * on 2017/10/10.
 */
@Repository
public class OrderDetailDao {
    private static final Logger log = LoggerFactory.getLogger(OrderDetailDao.class);

    @Autowired
    private RepairSql2oTemp sql2oTemp;




    /**
     * 工单详情（维修）
     * @return
     */
    public RepairOrderDetail getDetailByOrderId(JSONObject body) {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT o.ORDER_ID orderId, o.ORDER_CODE orderCode, o.CURRENT_TOTAL_KM currentTotalKm, ");
        sql.append(" fd.BLAME_TYPE blameType,c.KP_TIME as kpTime,o.UPDATE_TIME as overTime ,cm.CHASSIS_FACTORY as chassisFactoryName, cm.BODY_BRAND bodyFactoryName,");
        sql.append(" o.DRIVER_PHONE as driverPhone,o.DRIVER_NAME as driverName,  ");
        sql.append(" c.CAR_VIN carVin, o.CAR_NO carNo, c.TYPE_NAME carTypeName, c.COMPANY_NAME carCompany ");
        sql.append(" FROM T_REPAIR_ORDER o  ");
        sql.append(" LEFT JOIN t_car c ON o.CAR_ID = c.id ");
        sql.append(" LEFT JOIN T_FAULT_DIACRISIS fd ON o.ORDER_ID = fd.ORDER_ID ");
        sql.append(" LEFT JOIN T_CAR_MODEL cm ON cm.MODEL_CODE = c.CAR_MODEL ");
        sql.append(" WHERE o.ORDER_ID = :orderId ");
        log.debug(sql.toString());
        try (Connection con = sql2oTemp.getSql2o().open()) {
            Query query = con.createQuery(sql.toString());
            if (body.getString("orderId") != null) {
                query.addParameter("orderId", body.getString("orderId"));

            }
            return query.executeAndFetchFirst(RepairOrderDetail.class);
        }
    }
    /**
     * 工单详情（首保）
     * @return
     */
    public FirstInsuranceOrder getSbDetailByOrderId(JSONObject body) {
        String sql = "select FIO_ID orderId,CAR_NO carNo,CAR_OWNER carOwner,CAR_OWNER_ADDRESS carOwnerAdd,USER_NAME userName,USERE_ID_CARD userIdCard," +
                "USER_PHONE userPhone,USER_TELEPHONE userTelephone,FIRST_INSURANCE_DATE firstInsuranceDate, " +
                "INSURANCE_REAMRK insuranceRemark,ENGINEER_ID engineerId,REPAIR_ID repairId from t_first_insurance_order where FIO_ID =:orderId ";
        log.debug(sql);
        try (Connection con = sql2oTemp.getSql2o().open()) {
            Query query = con.createQuery(sql);
            if (body.getString("orderId") != null) {
                query.addParameter("orderId", body.getString("orderId"));

            }
            return query.executeAndFetchFirst(FirstInsuranceOrder.class);
        }
    }

    /**
     * 修改工单（维修）
     * @return
     */
    public Object editOrderByOrderId(JSONObject body) {
        String sql =" update T_REPAIR_RESULT set OLD_CODE = :oldCode,NOW_CODE = :nowCode WHERE ORDER_ID = :orderId ";
        log.debug(sql);
        Map<String,Boolean> m = new HashMap();
        try (Connection con = sql2oTemp.getSql2o().open()) {
            Query query = con.createQuery(sql);
            query.addParameter("oldCode", body.getString("oldCode"));
            query.addParameter("nowCode", body.getString("nowCode"));
            query.executeUpdate();
            m.put("state", Boolean.TRUE);
            return m;
        }catch (Exception e){
            log.debug(e.getMessage());
            m.put("state", Boolean.FALSE);
            return m;
        }
    }

    /**
     * 故障诊断接口
     * @return
     */
    public List<FaultDiacrisisParts> getGzzd(String orderId){
        StringBuilder sql = new StringBuilder();
        sql.append(" select COMPONENT_NAME componentName, DP_ID dpId  ");
        sql.append(" from T_FAULT_DIACRISIS_PARTS ");
        sql.append(" WHERE ORDER_ID = :orderId ");

        log.debug(sql.toString());
        try (Connection con = sql2oTemp.getSql2o().open()) {
            return con.createQuery(sql.toString()).addParameter("orderId", orderId).executeAndFetch(FaultDiacrisisParts.class);
        }
    }

    /**
     * 维修方案接口
     * @return
     */
    public List<RepairPlan> getWxfa(String orderId){
        StringBuilder sql = new StringBuilder();
        sql.append(" select PP_ID ppId, ORDER_ID orderId, ORDER_Code orderCode, PRICE_TYPE priceType, COMPONENT_DEC componentDec,  ");
        sql.append(" COMPONENT_NUMBER componentNumber, COMPONENT_PRICE componentPrice, REPAIR_ACTION repairAction ");
        sql.append(" from T_REPAIR_PLAN ");
        sql.append(" WHERE PRICE_TYPE <> 2 and ORDER_ID = :orderId ");

        log.debug(sql.toString());
        try (Connection con = sql2oTemp.getSql2o().open()) {
            return con.createQuery(sql.toString()).addParameter("orderId", orderId).executeAndFetch(RepairPlan.class);
        }
    }

    /**
     * 维修结果接口
     * 关系：一个维修方案有N个维修结果
     * @return
     */
    public List<RepairResult> getWxjg(String orderId){
        StringBuilder sql = new StringBuilder();
        sql.append(" select RESULT_ID resultId, ORDER_ID orderId, PLAN_ID planId, OLD_CODE oldCode, NOW_CODE nowCode ");
        sql.append(" from T_REPAIR_RESULT ");
        sql.append(" WHERE ORDER_ID = :orderId ");

        log.debug(sql.toString());
        try (Connection con = sql2oTemp.getSql2o().open()) {
            return con.createQuery(sql.toString()).addParameter("orderId", orderId).executeAndFetch(RepairResult.class);
        }
    }


    /**
     * 维修方案工时费接口
     * @return
     */
    public List<TbLaborCost> getWxfagsf(String orderId){
        StringBuilder sql = new StringBuilder();
        sql.append(" select lc.LABOR_COST_PRICE laborCostPrice, lc.REPAIR_PROJECT repairProject  ");
        sql.append(" from (select * from T_REPAIR_PLAN WHERE PRICE_TYPE=2 and ORDER_ID = :orderId) rp ");
        sql.append(" INNER JOIN t_labor_cost lc on rp.FK_ID = lc.id ");

        log.debug(sql.toString());
        try (Connection con = sql2oTemp.getSql2o().open()) {
            return con.createQuery(sql.toString()).addParameter("orderId", orderId).executeAndFetch(TbLaborCost.class);
        }
    }


    /**
     * 维修图片接口
     * @return
     */
    public List<OrderPic> getOrderPic(String orderId){
        String sql = "select ORDER_ID orderId, PIC_TYPE picType, PIC_PATH picPath from t_order_pic where ORDER_ID=:orderId ";
        log.debug(sql.toString());
        try (Connection con = sql2oTemp.getSql2o().open()) {
            return con.createQuery(sql).addParameter("orderId", orderId).executeAndFetch(OrderPic.class);
        }
    }



}
